package io.bdmc.modules.api.controller;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import io.bdmc.common.http.HttpAPIService;
import io.bdmc.common.http.HttpResult;
import io.bdmc.common.utils.Constant;
import io.bdmc.common.utils.MyMap;
import io.bdmc.common.utils.MyPage;
import io.bdmc.common.utils.R;
import io.bdmc.common.utils.WebTokenUtil;
import io.bdmc.common.validator.Assert;
import io.bdmc.common.wechatsdk.WeChatUtil;
import io.bdmc.modules.api.annotation.AuthIgnore;
import io.bdmc.modules.api.entity.SysValidate;
import io.bdmc.modules.api.service.ISysValidateService;
import io.bdmc.modules.api.service.TokenService;
import io.bdmc.modules.api.service.UserService;
import io.bdmc.modules.bss.entity.SmkAlarm;
import io.bdmc.modules.bss.entity.SmkDevice;
import io.bdmc.modules.bss.entity.SmkShop;
import io.bdmc.modules.bss.model.AlarmParam;
import io.bdmc.modules.bss.service.ISmkAlarmService;
import io.bdmc.modules.bss.service.ISmkDeviceService;
import io.bdmc.modules.bss.service.ISmkShopService;

/**
 * 用户相关接口，对应数据库Smk_Shop表的用户
 *
 * @author huang lu
 * @email hlkyo@qq.com
 * @date 2017-03-23 15:31
 */
@RestController
@RequestMapping("/api/customer")
public class CustomerController extends BaseApiController{
    @Autowired
    private UserService userService;
    @Autowired
    private TokenService tokenService;

    @Autowired
    private ISysValidateService _codeSvs;

    @Autowired
    private ISmkShopService _shopSvs;

    
    @Autowired
    private ISmkDeviceService _devSvs;

    @Autowired
    private ISmkAlarmService _alarmSvs;

    @Autowired
    private HttpAPIService _apiSVs;
    /**
     * 登录
     */
    @AuthIgnore
    @PostMapping("login")
    public R login(String mobile, String password){
        Assert.isBlank(mobile, "手机号不能为空");
        Assert.isBlank(password, "密码不能为空");

        //用户登录
        long userId = userService.login(mobile, password);

        //生成token
        Map<String, Object> map = tokenService.createToken(userId);

        return R.ok(map);
    }

    @AuthIgnore
    @PostMapping(value = "/verifycode")
    public R verifyCode(@RequestBody Map<String, Object> map) {
        String mobile = map.get("mobile").toString();
        int purpose = Integer.valueOf(map.get("purpose").toString());
        if (mobile == null || mobile.isEmpty()) {
            return R.error(-1, "手机号不能为空。");
        }
        if (purpose <= 0) {
            return R.error(-1, "参数不正确。");
        }
        QueryWrapper<SysValidate> w = new QueryWrapper<SysValidate>();
        w.eq("mobile", mobile).eq("is_used", false).eq("purpose", purpose);
        SysValidate code = _codeSvs.getOne(w);
        LocalDateTime lnow = LocalDateTime.now();
        if (code != null) {// 说明是再次发送获取验证码，判断间隔时间
            if (code.getSendTime() != null&&code.getSendTime().plusMinutes( Constant.INTERVAL).isBefore(lnow)) {// 时间间隔正常，可以再次发送本条验证码
                String verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);// 生成短信验证码
                SmsSingleSender ssender = new SmsSingleSender(Constant.SHORTMSGAPPID, Constant.SHORTMSGAPPKEY);
                String[] params = { verifyCode, String.valueOf(Constant.EXPIREMIN) };
                try {
                    SmsSingleSenderResult sendResult = ssender.sendWithParam("86", mobile, 195696, params, Constant.ShortMsgSign, "", "");
                    if (sendResult.result != 0) {
                        return R.error(-1, "短信发送失败，请联系客服人员。");
                    }
                } catch (Exception e) {
                   // logger.error(e.getMessage());
                    return R.error(-1, "短信发送失败，请联系客服人员。");
                }
                QueryWrapper<SmkShop> w1 = new QueryWrapper<SmkShop>();
                w1.eq("manager_mobile", mobile);
                List<SmkShop> shops = _shopSvs.list(w1);
                code.setValidateCode(verifyCode);
                code.setStartTime(lnow);
                code.setEndTime(lnow.plusMinutes( Constant.EXPIREMIN));
                code.setSendTime(lnow);
                _codeSvs.save(code);
                Map<String, Object> resultMap = new HashMap<String, Object>();
                resultMap.put("sendStat", "0");
                if (shops.size() > 0) {
                    resultMap.put("addr", shops.get(0).getAddr());
                    resultMap.put("shopName", shops.get(0).getShopName());
                    resultMap.put("managerName", shops.get(0).getManagerName());
                }
                return R.ok().putData(resultMap);
            } else {
                return R.error(-1, "请求时间过短 ，请稍后再试！");
            }
        } else {
            String verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);// 生成短信验证码
            SmsSingleSender ssender = new SmsSingleSender(Constant.SHORTMSGAPPID, Constant.SHORTMSGAPPKEY);
            String[] params = { verifyCode, String.valueOf(Constant.EXPIREMIN) };
            try {
                SmsSingleSenderResult sendResult = ssender.sendWithParam("86", mobile, 195696, params,  Constant.ShortMsgSign, "", "");
                if (sendResult.result != 0) {
                    return R.error(-1, "短信发送失败，请联系客服人员。");
                }
            } catch (Exception e) {
                //logger.error(e.getMessage());
                return R.error(-1, "短信发送失败，请联系客服人员。");
            }
            QueryWrapper<SmkShop> w1 = new QueryWrapper<SmkShop>();
                w1.eq("manager_mobile", mobile);
                List<SmkShop> shops = _shopSvs.list(w1);
            SysValidate newCode = new SysValidate();
            newCode.setMobile(mobile);
            newCode.setPurpose(purpose);
            newCode.setIsUsed(false);
            newCode.setValidateCode(verifyCode);
            newCode.setStartTime(lnow);
            newCode.setEndTime(lnow.plusMinutes( Constant.EXPIREMIN));
            newCode.setSendTime(lnow);
            _codeSvs.save(newCode);
            Map<String, Object> resultMap = new HashMap<String, Object>();
            resultMap.put("sendStat", "0");
            if (shops.size() > 0) {
                resultMap.put("addr", shops.get(0).getAddr());
                resultMap.put("shopName", shops.get(0).getShopName());
                resultMap.put("manageName", shops.get(0).getManagerName());
            }
            return R.ok().putData(resultMap);

        }
    }


    @AuthIgnore
    @PostMapping(value = "/bind")
    public R bind(@RequestBody Map<String, Object> map) {
        String mobile = String.valueOf(map.get("mobile"));
        String validateCode = String.valueOf(map.get("validateCode"));
        Integer purpose = Integer.valueOf(String.valueOf(map.get("purpose")));
        String openid = String.valueOf(map.get("openid"));
        String wxImage = String.valueOf(map.get("wxImage"));
        //String wxName = String.valueOf(map.get("wxName"));
        String shopName = String.valueOf(map.get("shopName"));
        String addr = String.valueOf(map.get("addr"));
        String managerName = String.valueOf(map.get("managerName"));

        if (mobile == null || validateCode == null || purpose == null || openid == null ) {
            return R.error(-1, "参数错误");
        }
        QueryWrapper<SysValidate> w = new QueryWrapper<SysValidate>();
        w.eq("mobile", mobile).eq("is_used", false).eq("purpose", purpose).eq("validate_code", validateCode);
        SysValidate vcode = _codeSvs.getOne(w);
        LocalDateTime now = LocalDateTime.now();
        if (vcode == null || vcode.getEndTime().isBefore(now)) {
            return R.error(-1, "验证码不存在或已过期，请重新获取。");
        }
        QueryWrapper<SmkShop> w1 = new QueryWrapper<SmkShop>();
        w1.eq("manager_mobile", mobile);
        List<SmkShop> shops = _shopSvs.list(w1);
        Boolean bindResult = false;
        String token = "";
        Map<String, Object> respMap = new HashMap<>();
        if (shops.size() <= 0) {// 新增
            SmkShop bd = new SmkShop();
            bd.setAddr(addr);
            bd.setShopName(shopName);
            bd.setManagerMobile(mobile);
            bd.setDeptId(1L);
            bd.setManagerName(managerName);
            bd.setOpenid(openid);
            bd.setWxImage(wxImage);
            bd.setWxName(shopName);
            bd.setJoinDate(now);
            _shopSvs.save(bd);
            bindResult = bd.getShopId() > 0;
            token = WebTokenUtil.createJWT(bd.getShopId(), bd.getOpenid(), bd.getDeptId(),bd.getWxName(), 36000000);
        } else {// 绑定所有同手机号店铺
            for (SmkShop b : shops) {
                b.setOpenid(openid);
                b.setWxImage(wxImage);
                b.setWxName(shopName);
            }
            bindResult = _shopSvs.updateBatchById(shops);
            token = WebTokenUtil.createJWT(shops.get(0).getShopId(), shops.get(0).getOpenid(),
                    shops.get(0).getDeptId(), shops.get(0).getWxName(), 36000000);
            //_redisUtils.
        }
        if (bindResult) {// 成功则使用验证码
            vcode.setIsUsed(true);
            _codeSvs.updateById(vcode);
            respMap.put("openid", openid);
            respMap.put("wxName", shopName);
            respMap.put("wxImage", wxImage);
            respMap.put("mobile", mobile);
            respMap.put("token", token);
            return R.ok().putData(respMap);
        } else {
            return R.error(-1, "服务器异常！");
        }
    }


    @PostMapping(value = "/getsign")
    public R getSign(@RequestBody Map<String, Object> map) {
        String url = String.valueOf(map.get("url"));
        if (url != null && url.length() > 0) {
            JSONObject sign = WeChatUtil.getSign(url);
            return R.ok().putData(sign);
        }
        return R.error(-1, "参数错误！");
    }

    //获取商户信息
    @PostMapping(value = "/shops")
    public R getShops() {
        String openid = getLoginName();
        if (StringUtils.isEmpty(openid)) {
            return R.error(-1, "openid为空");
        }
        QueryWrapper<SmkShop> w1 = new QueryWrapper<SmkShop>();
        w1.eq("openid", openid);
        List<SmkShop> shops = _shopSvs.list(w1);
        return R.ok().putData(shops);
    }

    @PostMapping(value = "/shopbyid")
    public R getShopsById(@RequestBody Map<String, Integer> map) {
        int id = map.get("id");
        SmkShop shop = _shopSvs.getById(id);
        return R.ok().putData(shop);
    }

       // 添加紧急联系人
       @PostMapping(value = "/addnotifier")
       public R addNotifyier(@RequestBody Map<String, Object> map) {
           String notify = String.valueOf(map.get("alarmNotifier"));
           int id = Integer.valueOf(String.valueOf(map.get("id")));
           if (id <= 0) {
               return R.error("参数错误！");
           }
           SmkShop s = _shopSvs.getById(id);
           // notify = buildings.getAlarmNotifier()+"|"+notify;
           s.setAlarmNotifier(notify);
           _shopSvs.updateById(s);
           return R.ok();
       }
   
       // 获取设备信息
       @PostMapping(value = "/devices")
       public R getSevices(@RequestBody Map<String, Integer> map) {
           int smkBuildingId = map.get("smkBuildingId");
           QueryWrapper<SmkDevice> w1 = new QueryWrapper<SmkDevice>();
           w1.eq("shop_id", smkBuildingId);
           List<SmkDevice> devices = _devSvs.list(w1);
           return R.ok().putData(devices);
       }

    // 获取报警信息
    @RequestMapping(value = "/alarmlist")
    public R alarmList(@RequestBody AlarmParam params) {
        String openid = getLoginName();
        MyPage<SmkAlarm> myPage = new MyPage<SmkAlarm>(params.getCurrent(), params.getSize());
        params.setOpenid(openid);
        MyPage<SmkAlarm> map = _alarmSvs.wxSelectAlarm(myPage, params);
		return R.ok().putData(MyMap.ok(map.getRecords(), map.getTotal()));
    }

    // 解除报警
    @PostMapping(value = "/relievealarm")
    public R relieveAlarm(@RequestBody Map<String, Object> map) {
        Integer alarmReason = 0;
        if( map.get("alarmReason") != null){
            alarmReason = Integer.valueOf(String.valueOf(map.get("alarmReason")));
        }
        if (map.get("alarmId") == null || map.get("dealMethod") == null || map.get("dealType") == null
                || map.get("dealResult") == null ) {
            return R.error(-1, "参数错误");
        }
        Integer id = Integer.valueOf(String.valueOf(map.get("alarmId")));
        Integer dealMethod = Integer.valueOf(String.valueOf(map.get("dealMethod")));
        Integer dealType = Integer.valueOf(String.valueOf(map.get("dealType")));
        String dealResult = String.valueOf(map.get("dealResult"));
        SmkAlarm alarm = _alarmSvs.getById(id);
        alarm.setDealMethod(dealMethod);
        alarm.setDealType(dealType);
        alarm.setDealResult(dealResult);
        alarm.setAlarmReason(alarmReason);
        alarm.setAlarmStat(2);
        _alarmSvs.updateById(alarm);
        if(alarm.getAlarmType().equals(2)){
            SmkDevice dev = _devSvs.getById(alarm.getDevId());
            try {
                HttpResult re = _apiSVs.doGetCommand(dev.getDevKey(), "5859");
                logger.debug("消音结果："+re.getCode()+"||"+re.getBody());
            } catch (Exception e) {
                logger.error(e.getMessage());
                e.printStackTrace();
            }
        }
        return R.ok();
    }

    @PostMapping(value = "/unbind")
    public R unbind(@RequestBody Map<String, Object> map) {
        //int id = Integer.valueOf(request.getAttribute("user_id").toString());
        // SmkShop b =_shopSvs.findOneById(id);
        String openid = getLoginName();
        QueryWrapper<SmkShop> w1 = new QueryWrapper<SmkShop>();
        w1.eq("openid", openid);
        List<SmkShop> shops = _shopSvs.list(w1);
        for (SmkShop b : shops) {
            if (b != null) {
                b.setWxImage("");
                b.setWxName("");
                b.setOpenid("");
                _shopSvs.updateById(b);
            }
        }
        return R.ok();
    }

}
